package com.itheima.ClassDemoWork;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/hack.html")
public class LoginFilter implements Filter {
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //your  code....
        //获取浏览器传入的数据
        HttpSession session = request.getSession();
        User  u = (User) session.getAttribute("u");
        if(u == null){
          //就说明没有登录成功
            //跳转到登录页面
            response.sendRedirect("/login.html");
        }else {
            //如果不等于null说明登录成功,就不过滤,让他访问到/hack.html页面
            chain.doFilter(request, response);
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
    }

}